package org.brownflat.watergate.job;

import org.apache.log4j.Logger;
import org.brownflat.watergate.domain.Branch;
import org.brownflat.watergate.domain.Commit;
import org.brownflat.watergate.domain.CommitBuilder;
import org.brownflat.watergate.scm.RepositoryClient;
import org.brownflat.watergate.scm.Revision;
import org.brownflat.watergate.scm.Revisions;
import org.brownflat.watergate.service.BranchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import static java.lang.String.format;

/**
 * <p>&copy Rupert Jones 2012</p>
 *
 * @author rup
 */
@Component("scanRevisionsJob")
@Scope("prototype")
public class ScanRevisionsJob implements Runnable {

    private static final Logger LOG = Logger.getLogger(ScanRevisionsJob.class);

    @Autowired
    private RepositoryClient repositoryClient;

    @Autowired
    private CommitBuilder commitBuilder;

    @Autowired
    private BranchService branchService;

    private int branchId = 0;

    @Override
    public void run() {
        Branch branch = branchService.findById(branchId);
        if(branchId == 0 || branch == null) {
            LOG.warn("Nothing to scan, no branch attached to this job.");
            return;
        } else {
            LOG.debug(format("Scanning branch [%s]...", branch.getName()));
        }

        Commit commit = branchService.findLastCommitFor(branch);
        long lastCommit = branch.getStartRevision();
        if(commit != null) {
            lastCommit = commit.getRevision();
        }

        Revisions remaining = repositoryClient.getRemainingRevisions(branch, lastCommit);
        int count = 0;
        for(Revision thisRevision : remaining) {
            Commit newCommit = commitBuilder.build(branch, thisRevision);
            branchService.save(newCommit);
            count++;
        }
        if(count > 0) {
            LOG.info(format("Completed scan for branch [%s], added [%s] commits.", branch.getName(), count));
        }
    }

    public void setBranchId(int id) {
        this.branchId = id;
    }
}
